var pp_finished = false;
var get_comments_finshed = false;
var comments_arr = {};
var total_answers = $('pre.answer').length;

function create_comment_info(comment_obj) {
    var info = $('<span class="info"></span>')
    var commenter = comment_obj['commenter_name'];
    var dt = comment_obj['modified'];
    info.html("<b>" + commenter + "</b> " + moment(dt).format('MMMM Do YYYY, h:mm:ss a'));
    return info;
}

function create_comment_div(comment_obj) {
    var comment = $('<div class="comment"></div>');

    var htmlstr = `
        <div class="update-comment well">
            <textarea class="commentarea form-control"></textarea>
            <button class="update btn btn-primary pull-right">update comment</button>
            <button class="cancel btn btn-default pull-right">cancel</button>
        </div>
        `;
    var form = $(htmlstr);
    form.attr('js-comment_id', comment_obj['id']);
    var ta = form.find('textarea');
    ta.val(comment_obj['content']);

    form.find('button.cancel').on("click", function(event) {
        $(this).parent().hide();
        $(this).parent().parent().find('div.view-comment').show();
        $(this).parent().parent().find('span.info').show();
    });

    form.find('button.update').on("click", function(event) {
        comment_obj = {};
        comment_obj['id'] = $(this).parent().attr('js-comment_id');
        comment_obj['content'] = $(this).parent().find('textarea').val();
        console.log(comment_obj);
        update_comment(comment_obj, $(this).parent().parent());
    });

    var view_comment = $('<div class="view-comment"></div>');
    var content = $('<span class="content"></span>');
    content.html(comment_obj['content']);
    var edit_btn = $('<span class="edit glyphicon glyphicon-pencil"></span>');
    edit_btn.on('click', function() {
        // show edit form and hide view
        // console.log('called');
        var form = $(this).parent().parent().find('div.update-comment');
        form.show();
        $(this).parent().hide();
        $(this).parent().parent().find('span.info').hide();
    });
    var delete_btn = $('<span class="delete glyphicon glyphicon-remove"></span></button>');
    delete_btn.attr('js-comment_id', comment_obj['id']);
    delete_btn.on("click", function(event) {
        comment_obj = {};
        comment_obj['id'] = $(this).attr('js-comment_id');
        delete_comment(comment_obj, $(this));
    });
    comment.append(create_comment_info(comment_obj));
    view_comment.append(content);
    if ($.py.current_user === comment_obj['commenter']) {
        view_comment.append(edit_btn);
        view_comment.append(delete_btn);
    }

    comment.append(form.hide());
    comment.append(view_comment)
    return comment;
}

function display_comments() {
    if (pp_finished === false || get_comments_finshed == false) {
        // console.log('wait for completion');
        return;
    }
    // console.log('display_comments');
    // console.log(comments_arr);
    for (i = 0; i < comments_arr.length; i++) {
        comment_obj = comments_arr[i];
        var answer_id = comment_obj['answer'];
        var is_amendment = comment_obj['is_amendment'];
        if (is_amendment === true) {
            var pre = $('#amendment-' + answer_id);
        }
        else {
            var pre = $('#answer-' + answer_id);
        }
        var index = comment_obj['linenum'];
        var li = pre.find('li').eq(index);
        var comment = create_comment_div(comment_obj);
        li.after(comment);
    }
}

function update_comment(comment_obj, comment_div){
    var url = "/exam/api/comments/" + comment_obj['id'] + "/";
    $.ajax({
        url: url,
        method: 'PATCH',
        data: {
            "content": comment_obj['content'],
        },
        context: {
            comment_div:comment_div,
        },
        success: function(data, textStatus, jqXHR) {
            console.log(url + ', textStatus: ' + textStatus + ', jqXHR: ' + jqXHR);
            console.log(data);
            // hide edit form and show view
            var span = comment_div.find('span.content');
            span.html(data.content);
            comment_div.find('div.update-comment').hide();
            comment_div.find('div.view-comment').show();
            comment_div.find('span.info').remove();
            comment_div.prepend(create_comment_info(data));
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(url + ', textStatus: ' + textStatus + ', jqXHR: ' + jqXHR);
            console.log(errorThrown);
        }
    });
}

function create_comment(comment_obj, btn, form){
    var url = "/exam/api/comments/";
    var post_data = {
        "answer": parseInt(comment_obj['answer']),
        "linenum": comment_obj['linenum'],
        "content": comment_obj['content'],
        "commenter": parseInt(comment_obj['commenter']),
        "is_amendment": (comment_obj['is_amendment'] == 'true'),
    }
    console.log(post_data);
    $.ajax({
        url: url,
        method: 'POST',
        data: post_data,
        context: {
            url:url,
        },
        success: function(data, textStatus, jqXHR) {
            console.log(url + ', textStatus: ' + textStatus + ', jqXHR: ' + jqXHR);
            console.log(data);
            btn.on("click", add_btn_clicked);
            // add edit view and normal view
            var li = btn.parent();
            form.remove();
            var comment = create_comment_div(data);
            var current_ele = li;
            while(true) {
                if (current_ele.next().is('div.comment')){
                    current_ele = current_ele.next();
                }
                else {
                    break;
                }
            }
            current_ele.after(comment);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(url + ', textStatus: ' + textStatus + ', jqXHR: ' + jqXHR);
            console.log(errorThrown);
        }
    });
}

function delete_comment(comment_obj, btn) {
    var url = "/exam/api/comments/" + comment_obj['id'] + "/";
    $.ajax({
        url: url,
        method: 'DELETE',
        data: {
            // "content": comment_obj['content'],
        },
        context: {
            url:url,
        },
        success: function(data, textStatus, jqXHR) {
            console.log(url + ', textStatus: ' + textStatus + ', jqXHR: ' + jqXHR);
            console.log(data);
            btn.parent().parent().find('span.info').remove();
            btn.parent().remove();
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(url + ', textStatus: ' + textStatus + ', jqXHR: ' + jqXHR);
            console.log(errorThrown);
        }
    });
}

function add_btn_clicked() {
    console.log($(this));

    var li = $(this).parent();
    if (li.nextAll('li').length) {
        if (li.nextAll('li').eq(0).prev('div.add-comment').length) {
            console.log('add-comment already exists');
            return;
        }
    }
    else {
        if (li.parent().children().last().hasClass('add-comment')) {
            console.log('add-comment already exists')
            return;
        }
    }

    var plus = $(this);
    var htmlstr = `
        <div class="add-comment well">
            <textarea class="form-control"></textarea>
            <button class="create btn btn-primary pull-right">create comment</button>
            <button class="cancel btn btn-default pull-right">cancel</button>
        </div>
        `;
    var form = $(htmlstr);
    var pre = li.parent().parent();
    form.find('button.cancel').on("click", function(event) {
        $(this).parent().remove();
        plus.on("click", add_btn_clicked);
    });
    form.find('button.create').on("click", function(event) {
        comment_obj = {};
        comment_obj['answer'] = pre.attr('js-answer');
        comment_obj['commenter'] = pre.attr('js-commenter');
        comment_obj['is_amendment'] = pre.attr('js-is_amendment');
        comment_obj['linenum'] = pre.find('li').index(li);
        comment_obj['content'] = $(this).parent().find('textarea').val();
        // console.log(comment_obj);
        create_comment(comment_obj, plus, form);
    });

    if (li.nextAll('li').length) {
        li.nextAll('li').eq(0).before(form);
    }
    else {
        li.parent().append(form);
    }
}

function printprint_finished() {
    console.log('pp_finished');

    pp_finished = true;
    display_comments();

    $('ol.linenums li').each(function() {
        var add_btn = $('<span class="glyphicon glyphicon-plus" style="margin-right:7px;"></span>');
        add_btn.on("click", add_btn_clicked);
        $(this).prepend(add_btn);
        $(this).children(':first').css("visibility","hidden");
        $(this).hover(
            function(){
                $(this).children(':first').css("visibility","visible");
            },function(){
                $(this).children(':first').css("visibility","hidden");
            });
    });
}

function load_all_comments() {
    // 获取所有answer的comments
    var url = "/exam/api2/" + $.py.exam_id + "/student/" + $.py.student_id + "/comments/";
    $.ajax({
        url: url,
        method: 'GET',
        data: {
        },
        context: {
            url:url,
        },
        success: function( result ) {
            console.log(url + ' return success!');
            console.log(result);
            // 显示该answer的comments
            comments_arr = result;
            get_comments_finshed = true;
            display_comments();
        }
    });
}
